import uuid
import os
import shutil

import datetime

import zipfile

def mani(path="./R/"):
    manifest = """
{
    "format_version": 1,
    "header": {
        "description": "A Picture Particle Resource",
        "name": "Minecraft Video Player Generate",
        "uuid": "2281e703-a42d-4683-96eb-e18daa08cdd0",
        "version": [0, 0, 1],
        "min_engine_version": [0, 0, 1]
    },
    "modules": [
        {
            "description": "bgArray",
            "type": "resources",
            "uuid": "2a407c8d-8b0a-44f0-b773-25cc1e81d5ec",
            "version": [0, 0, 1]
        }
    ]
}
    """
    new_manifest = (
        manifest.replace("2281e703-a42d-4683-96eb-e18daa08cdd0", str(uuid.uuid4()))
        .replace("2a407c8d-8b0a-44f0-b773-25cc1e81d5ec", str(uuid.uuid4()))
        .replace(
            "A Picture Particle Resource",
            "A Picture Particle Resource; date:" + str(datetime.datetime.now()),
        )
    )
    try:
        with open(path + "manifest.json", "w") as f:
            f.write(new_manifest)
    except FileNotFoundError as e:
        # print(e)
        if "./R/manifest.json" in str(e):
            # print("T")
            os.mkdir(path)
            with open(path + "manifest.json", "w") as f:
                f.write(new_manifest)
        else:
            return False

    # ------------------------


def parti():
    count = 0
    particle_json = """
{
    "format_version": "1.10.0",
    "particle_effect": {
        "description": {
            "identifier": "ssssssssssss",
            "basic_render_parameters": {
                "material": "particles_alpha",
                "texture": "kkkkkkkkkkkkkkkk"
            }
        },
        "components": {
            "minecraft:emitter_rate_instant": {
                "num_particles": 1
            },
            "minecraft:emitter_lifetime_once": {
                "active_time": 0.05
            },
            "minecraft:particle_lifetime_expression": {
                "max_lifetime": 0.05
            },
            "minecraft:particle_motion_dynamic": {
                "linear_acceleration": [
                    0,
                    0,
                    0
                ]
            },
            "minecraft:particle_appearance_billboard": {
                "size": [
                    16,
                    9
                ],
                "facing_camera_mode": "direction",
                "uv": {
                    "texture_width": 16,
                    "texture_heigth": 9,
                    "uv": [
                        0,
                        0
                    ],
                    "uv_size": [
                        16,
                        9
                    ]
                }
            }
        }
    }
}"""
    try:
        os.makedirs("./R/textures/particle/mvp/")
    except FileExistsError:
        pass
    try:
        os.makedirs("./R/particles/mvp/")
    except FileExistsError:
        pass

    # file_name_list = []
    for fn in os.listdir("./resources/"):
        if fn.endswith(".png"):
            # count += 1
            shutil.copy("./resources/" + fn, "./R/textures/particle/mvp/")
            # print("a")
            # print(count)
            # print("./R/particles/MVP/" + str(1) + ".json")
            # print("./R/particles/MVP/" + str(j + 1) + ".json")
            with open(
                "./R/particles/mvp/" + (kk := fn.replace(".png", "")) + ".json", "w"
            ) as w:
                thing = particle_json.replace(
                    "kkkkkkkkkkkkkkkk", "textures/particle/mvp/" + kk
                ).replace("ssssssssssss", kk)
                w.write(thing)


def compress_zipfile(sourceDir, outFilename, compression=8, exceptFile=None):
    """使用compression指定的算法打包目录为zip文件\n
    默认算法为DEFLATED(8),可用算法如下：\n
    STORED = 0\n
    DEFLATED = 8\n
    BZIP2 = 12\n
    LZMA = 14\n
    """

    zipf = zipfile.ZipFile(outFilename, "w", compression)
    pre_len = len(os.path.dirname(sourceDir))
    for parent, dirnames, filenames in os.walk(sourceDir):
        for filename in filenames:
            if filename == exceptFile:
                continue
            pathfile = os.path.join(parent, filename)
            arc_name = pathfile[pre_len:].strip(os.path.sep)  # 相对路径
            zipf.write(pathfile, arc_name)
    zipf.close()


if __name__ == "__main__":
    os.makedirs("./resources/",exist_ok=True)
    input("请将图片放入 ./resources/ 文件夹内，按下回车开始转换")
    mani()
    parti()
    compress_zipfile("./R/", "./result.mcpack")
    shutil.rmtree("./R/")
    input("转换完成，文件名为 result.mcpack，回车退出")
